<template>
  <!-- 弹窗 -->
  <el-dialog
    v-model="batch_import_data.show"
    title="批量导入积分"
    width="512px"
    @closed="handleClosed"
  >
    <div v-if="batch_import_data.step==0">

      <el-form label-width="120px">
        <el-form-item label="选择导入文件">
          <div style="width:320px">
            <el-upload
              drag
              :before-upload="beforeAvatarUpload"
              :action="UploadUrl"
              :show-file-list="false"
              accept=".xlsx"
              v-loading="batch_import_data.file_loading"
            >
              <div v-if="!batch_import_data.upload_state">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  拖拽文件或 <em>点击上传</em>
                </div>
              </div>
              <div v-else>
                <el-icon class="el-icon--upload">
                  <Document />
                </el-icon>
                <div class="el-upload__text">
                  <el-text>
                    已上传，准备导入数量：{{batch_import_data.data.integral.length}}
                  </el-text>
                </div>
              </div>
            </el-upload>
            <el-space>
              <el-text size="small">文件支持格式：.xlsx </el-text>
              <el-link
                size="small"
                type="primary"
                @click="handleDownTempFile"
              >下载模板</el-link>
            </el-space>
          </div>
        </el-form-item>
        <el-form-item label="导入积分类型">
          <el-select v-model="batch_import_data.data.type">
            <el-option
              label="全选"
              :value="3"
            ></el-option>
            <el-option
              label="城市赛积分"
              :value="1"
            ></el-option>
            <el-option
              label="锦标赛积分"
              :value="2"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            size="large"
            @click="batch_import_data.show=false"
          >取消</el-button>
          <el-button
            size="large"
            type="primary"
            :loading="batch_import_data.api_loading"
            @click="handleBatchImportIntegral"
          >导入</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-else-if="batch_import_data.step==1">
      <el-result
        icon="success"
        title="导入结束"
        :sub-title="'总共导入数量'+batch_import_data.data.integral.length+'人，成功'+batch_import_data.res.successNumber+'人，失败'+batch_import_data.res.failNumber+'人。'"
      >
        <!-- :sub-title="'总共导入数量'+batch_import_data.data.integral.length+'份'" -->
        <template #extra>
          <el-button
            size="large"
            @click="batch_import_data.step=0"
          >重新导入</el-button>
          <!-- <el-button
            size="large"
            type="warning"
          >详情</el-button> -->
          <el-button
            size="large"
            type="info"
            @click="batch_import_data.show=false"
          >关闭</el-button>
        </template>
      </el-result>
    </div>
  </el-dialog>
</template>

<script  setup>
import { ref } from "vue"
import { read, writeFile, utils } from 'xlsx'
import { saveAs } from 'file-saver';
import { ElMessage, ElNotification } from "element-plus";
import { ImportPointsApi } from "@/api";
const emit = defineEmits(['close'])
const Authorization = localStorage.getItem('token') ? localStorage.getItem('token') : "";
const baseURL = import.meta.env.VITE_MODE != 'dev' ? import.meta.env.VITE_API_HOST : '/api'
const UploadUrl = baseURL + "/api/uploadFile"
const batch_import_data = ref({
  show: false,
  file_loading: false,
  api_loading: false,
  upload_state: false,
  step: 0,
  data: {
    integral: [],
    type: 3
  },
  res: {

  }
})
/**
 * 上传前
 */
const beforeAvatarUpload = (rawFile) => {
  const type_arr = ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"];
  if (!type_arr.includes(rawFile.type)) {
    ElMessage.error('文件格式不正确!')
    return false
  }
  const size = 5;
  if (rawFile.size / 1024 / 1024 > size) {
    ElMessage.error('上传大小不得超过 ' + size + 'M')
    return false
  }
  handleFileToData(rawFile);
  //  读取文件
  return false
}
/**
 * 处理上传文件
 */
const handleFileToData = (file) => {
  batch_import_data.value.file_loading = true;
  const reader = new FileReader()
  reader.onload = (e) => {
    const { result } = e.target
    try {
      const workbook = read(result, { type: 'binary' })
      const json_data = utils.sheet_to_json(workbook.Sheets['积分']);
      batch_import_data.value.data.integral = json_data.map((item) => {
        return {
          studentId: item['ID'],
          cityIntegral: item['城市赛积分'] ?? null,
          championship: item['锦标赛积分'] ?? null,
        }
      }).filter((item) => {
        return item.studentId
      })
      batch_import_data.value.upload_state = true;

    } catch (error) {

    }
    batch_import_data.value.file_loading = false;

  }
  reader.onerror = () => {
    batch_import_data.value.file_loading = false;
  }
  //   reader.readAsBinaryString(file)
  reader.readAsArrayBuffer(file)
}
/**
 * 下载上传模板
 */
const handleDownTempFile = () => {

  const data = [{
    'ID': 10001,
    '城市赛积分': 0,
    '锦标赛积分': 0
  }
  ];
  // 新建空workbook，然后加入worksheet
  const ws = utils.json_to_sheet(data)
  // 设置每列的列宽，10代表10个字符，注意中文占2个字符
  ws['!cols'] = [
    { wch: 10 },
    { wch: 30 },
    { wch: 25 }
  ]
  // 新建book
  const wb = utils.book_new()
  // 生成xlsx文件(book,sheet数据,sheet命名)
  utils.book_append_sheet(wb, ws, '积分')
  // 写文件(book,xlsx文件名称)
  let blob = writeFile(wb, '批量导入积分模板.xlsx')
  //   let blob = new Blob(text_data, { type: "text/csv;charset=utf-8" });
  ElMessage.success("正在导出");
  saveAs(blob);
}

/**
 * 开始导入
 */
const handleBatchImportIntegral = async () => {
  batch_import_data.value.api_loading = true;
  let res = await ImportPointsApi(batch_import_data.value.data)
  if (res.success) {
    ElNotification({
      title: '成功',
      message: res.message,
      type: 'success',
    })
    batch_import_data.value.step = 1
    batch_import_data.value.res = res.entity;
  } else {
    ElMessage.error(res.message)
  }
  batch_import_data.value.api_loading = false;
}
/**
 * 打开批量导入积分的弹窗
 */
const handleOpenModal = () => {
  batch_import_data.value.show = true;
  batch_import_data.value.step = 0;
  batch_import_data.value.upload_state = false;
  batch_import_data.value.data.integral = [];
  batch_import_data.value.data.type = 3;
}
const handleClosed = () => {
  emit('closed')
}
defineExpose({
  handleOpenModal
})
</script>

<style lang="scss" scoped></style>